package com.example.game;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

public class GameView extends View {
	private ImageButton MainNewGame;
	private final int UP = 0, DOWN = 1, LEFT = 2, RIGHT = 3,
			ComputerWhoPlay = 1, ComputerId = 2, VSComputer = 2;
	private Board board;
	private Boolean board_created = false;
	private Player[] p = new Player[2];
	public int whoPlay, playId; // 0=player 1 , 1 =player 2
	private Paint line, bg, sel;
	private int horSX[], horEX[], horY[], width, height, nei[][];
	private int fromID = -1, toID = -1, selCell = 0, eatID = -1;
	private Context context;
	// Example to draw image
	Drawable m, bigSqaureDraw, middleSquareDraw, smallSquareDraw, horBarDraw,
			verBarDraw, cellDraw, whiteWin, blackWin, youWin, youLose;
	Drawable cellSelDraw;
	private int d = 15;
	private Rect[] rect;
	public Boolean changed=false;
	public String message=""; 
	Handler playHandler=null;
	public final int PLAYCHANGED=1;
	private computer computerPlayer = new computer(ComputerId);

	public GameView(Context context, int playId) {
		super(context);
		this.context = (Activity) context;
		this.playId = playId;
		board = new Board();
		m = context.getResources().getDrawable(R.drawable.coin1);
		bigSqaureDraw = context.getResources().getDrawable(
				R.drawable.bigest_square);
		middleSquareDraw = context.getResources().getDrawable(
				R.drawable.middle_squra);
		smallSquareDraw = context.getResources().getDrawable(
				R.drawable.small_square);
		horBarDraw = context.getResources().getDrawable(
				R.drawable.horizontal_bar);
		verBarDraw = context.getResources()
				.getDrawable(R.drawable.vertical_bar);
		cellDraw = context.getResources().getDrawable(R.drawable.circle);
		cellSelDraw = context.getResources().getDrawable(
				R.drawable.circle_selected);
		blackWin = context.getResources().getDrawable(R.drawable.black_win);
		whiteWin = context.getResources().getDrawable(
				R.drawable.white_player_win);
		youLose = context.getResources().getDrawable(R.drawable.you_lose);
		youWin = context.getResources().getDrawable(R.drawable.you_win);
		whoPlay = 0;
		line = new Paint();
		line.setColor(Color.RED);
		sel = new Paint();
		sel.setColor(Color.CYAN);
		bg = new Paint();
		bg.setColor(Color.rgb(47, 137, 204));
		p[0] = new Player(board);
		p[0].setDrawable(context.getResources().getDrawable(R.drawable.coin1));
		p[1] = new Player(board);
		p[1].setDrawable(context.getResources().getDrawable(R.drawable.coin2));
		setFocusable(true);
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		width = w;
		height = h;
		if (w != 480) {
			float rate = 480 / (float) w;
			float dd = (rate < 1) ? 15 * rate : -15 / rate;
			d += (int) dd;
		}

		super.onSizeChanged(w, h, oldw, oldh);
	}

	// Updating Board with drawable contents
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		canvas.drawRect(0, 0, width, height, bg);
		if (!board_created) {
			board.createBoard(playId, canvas.getWidth(), canvas.getHeight());
			board_created = true;
			horSX = board.getHorSX();
			horEX = board.getHorEX();
			horY = board.getHorY();
			nei = board.getNeighbours();
			rect = board.getRect();
			bigSqaureDraw.setBounds(horSX[0], horY[0], horEX[0], horY[7]);
			middleSquareDraw.setBounds(horSX[1], horY[1], horEX[1], horY[6]);
			smallSquareDraw.setBounds(horSX[2], horY[2], horEX[2], horY[5]);
		}
		bigSqaureDraw.draw(canvas);
		middleSquareDraw.draw(canvas);
		smallSquareDraw.draw(canvas);
		horBarDraw.setBounds(rect[9].left + d / 4, rect[9].top + d / 4,
				rect[11].left, rect[9].bottom - d / 4);
		horBarDraw.draw(canvas);
		horBarDraw.setBounds(rect[12].left + d / 4, rect[12].top + d / 4,
				rect[14].right, rect[12].bottom - d / 4);
		horBarDraw.draw(canvas);
		verBarDraw.setBounds(rect[1].left + d / 4, rect[1].top + d / 2,
				rect[1].left + d / 2 + d, rect[7].top + d / 2);
		verBarDraw.draw(canvas);
		verBarDraw.setBounds(rect[16].left + d / 4, rect[16].top + d / 2,
				rect[16].left + d / 2 + d, rect[22].top + d / 2);
		verBarDraw.draw(canvas);
		for (int i = 0; i < rect.length; i++) {
			cellDraw.setBounds(rect[i]);
			cellDraw.draw(canvas);
		}
		if (fromID != -1) {
			cellSelDraw.setBounds(rect[fromID]);
			cellSelDraw.draw(canvas);
		}
		cellSelDraw.setBounds(rect[selCell]);
		cellSelDraw.draw(canvas);
		p[0].drawCoins(canvas, rect);
		p[1].drawCoins(canvas, rect);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		invalidate();
		if(!isMyTurn()) return true;
		switch (keyCode) {
		case KeyEvent.KEYCODE_W:
		case KeyEvent.KEYCODE_DPAD_UP:
			select(nei[selCell][UP]);
			break;
		case KeyEvent.KEYCODE_S:
		case KeyEvent.KEYCODE_DPAD_DOWN:
			select(nei[selCell][DOWN]);
			break;
		case KeyEvent.KEYCODE_D:
		case KeyEvent.KEYCODE_DPAD_RIGHT:
			select(nei[selCell][RIGHT]);

			break;
		case KeyEvent.KEYCODE_A:
		case KeyEvent.KEYCODE_DPAD_LEFT:
			select(nei[selCell][LEFT]);
			break;
		case KeyEvent.KEYCODE_SPACE:
		case KeyEvent.KEYCODE_DPAD_CENTER:
			operationsOnSelected();
			break;
		default:
			return super.onKeyDown(keyCode, event);
		}
		invalidate();
		if (board.playType == VSComputer && whoPlay == ComputerWhoPlay) {
			operationsOnSelected();
		} else if (p[whoPlay].canPlay(p[(whoPlay + 1) % 2]) == false) {
			finishGame();
		}
		return true;

	}

	// @Override
	public boolean onTouchEvent(MotionEvent event) {
		if(!isMyTurn()) return true;
		Point touchPosition = new Point((int) event.getX(), (int) event.getY());
		int id = board.getId(touchPosition);
		if (id >= 0 && id <= 23) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_UP:
				manageSelectMove(id);
				break;
			}
		}
		invalidate();
		if (board.playType == VSComputer && whoPlay == ComputerWhoPlay) {
			operationsOnSelected();
		} else if (p[whoPlay].canPlay(p[(whoPlay + 1) % 2]) == false) {
			finishGame();
		}
		return true;
	}

	private void select(int id) {
		selCell = id;
	}

	private void unSelect() {
		selCell = -1;
	}

	private void manageSelectMove(int touchedId) {
		if (selCell == touchedId) {
			operationsOnSelected();
		} else {
			select(touchedId);
		}
	}

	private void operationsOnSelected() {
		if (p[whoPlay].canPlay(p[(whoPlay + 1) % 2]) == false) {
			finishGame();
		}

		if (eatID == -2) {
			if (board.playType == VSComputer && whoPlay == ComputerWhoPlay) {
				computerPlayer.playerOne = p[0];
				computerPlayer.playerTwo = p[1];
				selCell = computerPlayer.eat();
			}
			if (p[(whoPlay + 1) % 2].findCellInCoins(selCell) != -1) {
				if (p[(whoPlay + 1) % 2].canEat(selCell) == false
						|| p[(whoPlay + 1) % 2].canEatString()) {
					nextPlayer();
					p[whoPlay].clearCell(selCell);
					eatID = -1;
				}
				setState(PLAYCHANGED);
				message="e"+Integer.toString(selCell);
			}
		} else if (p[whoPlay].finishedPush() == false) {
			if (board.playType == VSComputer && whoPlay == ComputerWhoPlay) {
				computerPlayer.playerOne = p[0];
				computerPlayer.playerTwo = p[1];
				selCell = computerPlayer.push();
			}
			if (p[0].findCellInCoins(selCell) == -1
					&& p[1].findCellInCoins(selCell) == -1) {
				p[whoPlay].pushCoin(selCell);
				if (p[whoPlay].canEat(selCell))
					eatID = -2;
				else
					nextPlayer();
				setState(PLAYCHANGED);
				message="p"+Integer.toString(selCell);
			}
		} else if (fromID == -1) {
			if (board.playType == VSComputer && whoPlay == ComputerWhoPlay) {
				computerPlayer.playerOne = p[0];
				computerPlayer.playerTwo = p[1];
				Move getMove = computerPlayer.move();
				fromID = getMove.from;
				toID = getMove.to;
			}
			if (p[whoPlay].findCellInCoins(selCell) != -1)
				fromID = selCell;
		} else {// move
			if (board.playType == VSComputer && whoPlay == ComputerWhoPlay)
				selCell = toID;
			if (p[0].findCellInCoins(selCell) == -1
					&& p[1].findCellInCoins(selCell) == -1) {
				if (p[whoPlay].moveCoin(fromID, selCell)) {
					int bfrom=fromID;
					fromID = -1;
					if (p[whoPlay].canEat(selCell))
						eatID = -2;
					else
						nextPlayer();
					setState(PLAYCHANGED);
					message="m"+Integer.toString(bfrom)+","+Integer.toString(selCell);
				}
			} else
				fromID = -1;
		}
		if (board.playType == VSComputer && whoPlay == ComputerWhoPlay) {
			operationsOnSelected();
		}
	}

	private void nextPlayer() {
		whoPlay++;
		whoPlay %= 2;
	}

	private void finishGame() {
		int sdk = android.os.Build.VERSION.SDK_INT;
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		View view = new View(context);

		if (whoPlay == 0 && board.playType == VSComputer) {
			if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
				view.setBackgroundDrawable(youLose);
			} else {
				view.setBackground(youLose);
			}
		} else if (whoPlay == 1 && board.playType == VSComputer) {
			if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
				view.setBackgroundDrawable(youWin);
			} else {
				view.setBackground(youWin);
			}
		} else if (whoPlay == 0) {
			if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
				view.setBackgroundDrawable(blackWin);
			} else {
				view.setBackground(blackWin);
			}
		} else {
			if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
				view.setBackgroundDrawable(whiteWin);
			} else {
				view.setBackground(whiteWin);
			}
		}
		builder.setView(view);
		final AlertDialog finishDialog = builder.create();
		finishDialog.show();

		int secondsDelayed = 10;
		new Handler().postDelayed(new Runnable() {
			public void run() {
				Log.d("maged", "dismiss");
				finishDialog.dismiss();
				Intent intent = new Intent(context, main.class);
				context.startActivity(intent);
				// ((Activity)context).finish();
			}
		}, secondsDelayed * 1000);

	}
	public Boolean isMyTurn(){
		if(playId<3) return true;
		if(playId==3 && whoPlay==0)
		return true;
		if(playId==4 && whoPlay==1)
		return true;
		return false;
	}
	public void multiplayer(int position){
		selCell=position;
		operationsOnSelected();
		invalidate();
	}
    /**
     * Set the current state of the chat connection
     * @param state  An integer defining the current connection state
     */
    private synchronized void setState(int state) {
    	if(playHandler!=null)
        // Give the new state to the Handler so the UI Activity can update
        playHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
    }
}
